package com.ly.hotel;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.model.Device;
import com.ly.hotel.model.Soft;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.CloseActivityEvent;
import com.ly.hotel.msgevent.NetworkEvent;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.timetask.CallStatusSyncTimerTask;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.ShellTools;
import com.ly.hotel.util.TipsUtil;
import com.ly.hotel.util.TouchUtil;
import com.ly.hotel.util.WebInstaller;
import com.ly.hotel.view.InitActivity;
import com.ly.hotel.view.common.CloudAdShowActivity;
import com.ly.hotel.view.common.CustomDialog;
import com.ly.hotel.view.liuwei.InputHandNoActivity;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.bugly.crashreport.CrashReport.UserStrategy;

import de.greenrobot.event.EventBus;

public class MyBaseActivity extends Activity {

	protected MyApplication app;
	private static final int SYNC_CALL = 1;
	private static final int UPDATE_SPA =  7;
	private static final int INSTALL_HELPER =  8;
	private static final int INSTALL_PLAYER =  9;
	public String className = "未知类";
	public ThisHandler handlerMsg = new ThisHandler(this);
	public Context mcontext;
	public boolean firstInit = true;
	public boolean waitSetting = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(!MyApplication.isSelectLang){
			Intent lIntent = new Intent(this,InitActivity.class);
			startActivity(lIntent);
			finish();
		}else {
			className = getClass().getSimpleName();
			Log.i("MyBaseActivity", className + "->onCreate");
			app = (MyApplication) getApplication();
			mcontext = getBaseContext();
			EventBus.getDefault().register(this);
			if (app.getBtnItemInfo().size() == 0) {
				Log.i("MyBaseActivity", "重新初始化导航栏数据");
			}
		}
	}

	public void initBugly() {
		PackageManager pm = this.getPackageManager();
		int flags = PackageManager.GET_UNINSTALLED_PACKAGES;
		PackageInfo pkgInfo = null;
		try {
			pkgInfo = pm.getPackageInfo("com.ly.hotel", flags);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		try {
			UserStrategy strategy = new UserStrategy(getApplicationContext());
			strategy.setAppChannel(URLDecoder.decode(MyApplication.authToCompany, "UTF-8"));
			strategy.setAppVersion(pkgInfo.versionName + "." + pkgInfo.versionCode);
			strategy.setAppPackageName("com.ly.hotel");
			CrashReport.setUserId(MyApplication.getMAC()); // 设置用户的唯一标识
			CrashReport.initCrashReport(getApplicationContext(), "900004580", true, strategy); // 初始化SDK,true代表App处于调试阶段，false代表App发布阶段
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void checkInternet(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				if(NetworkUtil.ping("www.baidu.com")){
					Log.e("cloud_alive", "初始化bug管理系统...");
					initBugly();
				}
			}
		}).start();
	}
	@Override
	protected void onDestroy() {
		Log.i("MyBaseActivity", className + "->onDestroy");
		super.onDestroy();
		// unregisterReceiver(mHomeKeyEventReceiver);
		EventBus.getDefault().unregister(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if(firstInit){
			update();
//			checkVodPlayer();
			checkLyHelper();
			
			firstInit = false;
		}
	}

	/*
	 * 网络状态变化
	 */
	public void onEventMainThread(NetworkEvent e) {
		Log.i("network","网络状态变化................." + e.isOk());
		synchronized (this) {
			if (e.isOk()) {// 去登陆
				// login();
			} else {
				// 提示网络不通
				TipsUtil.networkUnable(this);
			}
		}
	}
	
	public void onEventMainThread(CloseActivityEvent e) {
		this.finish();
	}


	public void update_date_time(Device d) throws IOException {
		Log.i("date", "获取服务器时间:" + d.getNow().toString());

		// 根据服务器的时间设置一下本地的日历
		int year = d.getNow().getYear() + 1900; // 月份
		int month = d.getNow().getMonth() + 1; // 日期
		int date = d.getNow().getDate();
		int hour = d.getNow().getHours(); // 小时
		Log.i("date", "解析服务器的日期：" + year + "-" + month + "-" + date + " "
				+ hour);
		
		MyApplication.startUpTimeHour = hour;
		MyApplication.startUpTime = year + "-" + month + "-" + date;
	}

	// 解决Android中多次点击启动多个相同界面的问题
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			if (TouchUtil.isFastDoubleClick()) {
				Log.i("MyBaseActivity", "忽略重复的点击");
				return true;
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	protected void tv(Context context){
		Log.i("live","准备播放电视");
		if(TextUtils.isEmpty(SysConf.extendConfGetValue(SysConf.SYS_CONF_IPTV_PACKET_NAME,""))){
			if(className != null && !className.equals("com.ly.hotel.view.live.LiveActivity")){
//				..调用广告页面来跳转页面
				if(Build.BOARD.equals(Constants.BOARD_TYPE_ADA801_NAME)){
//					this.startActivity(new Intent(this, TvActivity1.class));
					Intent intent = new Intent(getBaseContext(), CloudAdShowActivity.class);
					intent.putExtra("actionType", "tv");
					startActivity(intent);
				}else if(Build.BOARD.equals(Constants.BOARD_TYPE_ADA628_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_6A638_NAME)
						 || Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
					Intent intent = new Intent(getBaseContext(), CloudAdShowActivity.class);
					intent.putExtra("actionType", "tv");
					startActivity(intent);
				}
			} 
		}else{
			boolean downloadFlag = false;
			String packName = SysConf.extendConfGetValue(SysConf.SYS_CONF_IPTV_PACKET_NAME, "");
			if(!packName.equals("") && AppUtil.checkAppIsExist(context, packName)){
//				..调用广告页面来跳转页面
				Log.i("live","打开IPTV,包名:" + packName);
				Intent intent = new Intent(getBaseContext(), CloudAdShowActivity.class);
				intent.putExtra("actionType", "tv_3td");
				intent.putExtra("apkName", packName);
				startActivity(intent);
			}else{
				Log.i("live","不能打开IPTV,包名:" + packName + ":" + AppUtil.checkAppIsExist(context, packName));
				downloadFlag = true;
			}

			if(downloadFlag){
				Log.i("live", "下载路径:" + MyApplication.getHostResUrl() + "/upload/tv/" + Constants.CUSTOM_TV_APK_FILE_NAME);
				new WebInstaller(context, MyApplication.getHostResUrl() + "/upload/tv/"
						+ Constants.CUSTOM_TV_APK_FILE_NAME, Constants.CUSTOM_TV_APK_ROOT, Constants.CUSTOM_TV_APK_FILE_NAME).downloadAndInstall();
			}
		}
	}
	
	public void liuwei(Context context) {
		InputHandNoActivity dialog = new InputHandNoActivity(context, R.style.InputDialog);// 创建Dialog并设置样式主题
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_LIUWEI_WAIT));
	}

	public void call() {
		Log.i("MyBaseActivity", "初始化呼叫确定框");
		String callTips="";
		if(app.getCallStatus() == Constants.CALL_CANCLE){
			callTips = getString(R.string.call_warning_sure);
		}else if(app.getCallStatus() == Constants.CALL_REQUEST){
			callTips = getString(R.string.call_warning_cancle);
		}
		
		CustomDialog.Builder builder = new CustomDialog.Builder(getBaseContext()).setTitle(callTips)
				.setFirstButton(getString(R.string.WarningYes), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface di, int arg1) {
						
//						if (app.isService()) {
							new Thread(new Runnable() {
								@Override
								public void run() {
									String rv = "";
									rv = app.changeLight();
									Message msg = new Message();
									Bundle data = new Bundle();
									data.putString("msg", rv);
									msg.setData(data);
									msg.what = SYNC_CALL;
									handlerMsg.sendMessage(msg);
								}

							}).start();
							
							if(app.getCallStatus() == Constants.CALL_CANCLE){
								EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_CALL_PREFIX + "呼叫"));
							}else{
								EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_CALL_PREFIX + "取消呼叫"));
							}
							
							di.dismiss();
//						}
//						Toast.makeText(getBaseContext(), "请求成功", Toast.LENGTH_LONG).show();
					}
				}).setSecondButton(getString(R.string.WarningNo), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface di, int arg1) {
						di.dismiss();
					}
				});

		CustomDialog ad = builder.create();
		ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		ad.show();
		ad.getWindow().setLayout(getResources().getDimensionPixelSize(R.dimen.px450),
				getResources().getDimensionPixelSize(R.dimen.px300));
	}

	// 升级
	private void update() {
		// 更新（升级）
		/*
		 * 加入线程池会导致不能运行
		 * */
		new Thread() {
			@Override
			public void run() {
				Log.i("initData", "准备检测升级...........");
				while(!MyApplication.serverAssess){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				int version = AppUtil.getVersion(MyBaseActivity.this, MyBaseActivity.this.getPackageName());//版本号
				String versionName = AppUtil.getVersionName(MyBaseActivity.this, MyBaseActivity.this.getPackageName());//主版本号
				Log.i("initData", "当前版本:" + versionName + "." +version);
				MyApplication.spaVersion = versionName + "." +version;
				Soft soft = SPAService.checkSoftUpdate(MyApplication.getMAC() ,versionName, version);
				if (soft != null) {
					Log.i("initData", "服务器升级文件版本:" + soft.getVersion());
				}

				app.setSoftUpdate(soft);

				if ((soft != null && version < soft.getVersion())) {

					Log.i("initData", "updateReceiver..准备更新..");
					if (handlerMsg.hasMessages(UPDATE_SPA)) {
						handlerMsg.removeMessages(UPDATE_SPA);
					}

					handlerMsg.sendEmptyMessageDelayed(UPDATE_SPA, 1000);
				}
			}
		}.start();
	}

	private void checkLyHelper(){
		boolean needInstall = false;
		int playerVersion = 0;
		int newPlayerVersion = 0;
		if(getMyBoard() ){
		//判断是否安装了spaHelper
			if(AppUtil.checkAppIsExist(this, Constants.SPA_HELPER_PACKET_NAME)){
				playerVersion = AppUtil.getVersion(this, Constants.SPA_HELPER_PACKET_NAME);
				Log.i("init", "已经安装了helper,版本号=" + playerVersion);
			} else{
				needInstall = true;
			}
			
			File dir = getDir("spadownload", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE
					| Context.MODE_WORLD_WRITEABLE);
			dir.mkdirs();
			
			String LoclePath = dir.getAbsolutePath() + "/" + Constants.SPA_HELPER_FILE_NAME;
			Log.i("init", "本地文件路径->" + LoclePath);
			
			File file = new File(LoclePath);
			if(file.exists()){
				file.delete();
			}
			
			if(AppUtil.copyApkFromAssets(this, Constants.SPA_HELPER_FILE_NAME, LoclePath)){
				newPlayerVersion = AppUtil.getArchiveVersion(this,LoclePath);
				Log.i("init", "spa包内helper版本是->" + newPlayerVersion);
				if(newPlayerVersion > playerVersion){
					Log.i("init", "这是个新版本helper，更新之");
					needInstall = true;
				}
			}
				
			if(needInstall){
				Log.i("init", "没有helper或者版本过低，安装之！");
				Message msg = new Message();
				msg.what = INSTALL_HELPER;
				Bundle b = new Bundle();
				b.putString("path", LoclePath);
				msg.setData(b);
				handlerMsg.sendMessageDelayed(msg, 3000);
			}
		}
	}
	
	private void checkVodPlayer(){
		boolean needInstall = false;
		int playerVersion = 0;
		int newPlayerVersion = 0;
		Log.i("vod", "主板类型:" + Build.BOARD);
		if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME) || Build.BOARD.endsWith(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)){
			//判断是否安装了播放器
			if(AppUtil.checkAppIsExist(this, Constants.SPA_PLAYER_PACKET_NAME)){
				playerVersion = AppUtil.getVersion(this, Constants.SPA_PLAYER_PACKET_NAME);
				Log.i("vod", "已经安装了播放器,版本号=" + playerVersion);
			} else{
				needInstall = true;
			}
			
			File dir = this.getDir("spadownload", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE
					| Context.MODE_WORLD_WRITEABLE);
			dir.mkdirs();
			
			String LoclePath = dir.getAbsolutePath() + "/" + Constants.SPA_PLAYER_FILE_NAME;
			Log.i("vod", "本地文件路径->" + LoclePath);
			
			File file = new File(LoclePath);
			if(file.exists()){
				file.delete();
			}
			
			if(AppUtil.copyApkFromAssets(this, Constants.SPA_PLAYER_FILE_NAME, LoclePath)){
				newPlayerVersion = AppUtil.getArchiveVersion(this,LoclePath);
				Log.i("vod", "spa包内player版本是->" + newPlayerVersion);
				if(newPlayerVersion > playerVersion){
					Log.i("vod", "这是个新版本播放器，更新之");
					needInstall = true;
				}
			}
				
			if(needInstall){
				Log.i("vod", "没有播放器或者版本过低，安装之！");
				Toast.makeText(this, "没有播放器或者版本过低，准备安装，请稍后", Toast.LENGTH_LONG).show();
				Message msg = new Message();
				msg.what = INSTALL_PLAYER;
				Bundle b = new Bundle();
				b.putString("path", LoclePath);
				msg.setData(b);
				handlerMsg.sendMessageDelayed(msg, 1000);
			}
	
		}
	}

	//判断是否触摸设备
	public boolean getMyTouchBoard(){
		boolean isMyBoard = false;
		if(Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)
				|| Build.BOARD.equals(Constants.BOARD_TYPE_ADA801_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA628_NAME)
				|| Build.BOARD.endsWith(Constants.BOARD_TYPE_RK3288_NAME) && Build.BOARD.endsWith(Constants.BOARD_TYPE_MSM8974_NAME)){
			isMyBoard = true;
		}
		return isMyBoard;
	}

	//判断是否正式设备
	public static boolean getMyBoard(){
		boolean isMyBoard = false;
		if(Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA648_NAME)
				|| Build.BOARD.equals(Constants.BOARD_TYPE_ADA801_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_ADA628_NAME)
				|| Build.BOARD.equals(Constants.BOARD_TYPE_S905_NAME) || Build.BOARD.equals(Constants.BOARD_TYPE_S905_WY_NAME)
				|| Build.BOARD.equals(Constants.BOARD_TYPE_HI_3798) && Build.PRODUCT.equals("Hi3798MV100")){
			isMyBoard = true;
		}
		return isMyBoard;
	}
	
	public static class ThisHandler extends Handler {
		private WeakReference<MyBaseActivity> wrActivity;

		public ThisHandler(MyBaseActivity activity) {
			wrActivity = new WeakReference<MyBaseActivity>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			final MyBaseActivity act = wrActivity.get();
			if (act != null) {
				switch (message.what) {

				case SYNC_CALL:
					String jsonStr = message.getData().getString("msg");
					if(jsonStr != null && !jsonStr.equals("")){
						Toast.makeText(act.getBaseContext(), jsonStr, Toast.LENGTH_SHORT).show();
					}
					
					//呼叫指令发出后，再次同步一次，这样保证实时性
					SPABackService.getThreadPool().schedule(new CallStatusSyncTimerTask(), 200, TimeUnit.MILLISECONDS);
					SPABackService.getThreadPool().schedule(new CallStatusSyncTimerTask(), 500, TimeUnit.MILLISECONDS);
					
					break;
					
				case INSTALL_HELPER:
					final String LoclePath1 = message.getData().getString("path");
					if(MyApplication.canRunRootCommands){
						Log.i("helper", "正在安装->" + LoclePath1);
						//权限修改
						ShellTools ex = new ShellTools();
						String[] cmd = { "chmod", "777", LoclePath1 };
						try {
							ex.execute(cmd, "/");
						} catch (IOException e) {
							e.printStackTrace();
						}	
	
						Log.i("helper", "使用命令升级apk");
						String[] cmd1 = { "pm", "install", "-r", LoclePath1 };
						 String result = null;
						 File dir = act.getDir("spadownload", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE
									| Context.MODE_WORLD_WRITEABLE);
						try {
							result = ex.execute(cmd1, dir.getAbsolutePath()+"/");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Log.i("helper", "安装结果:" + result);
						Toast.makeText(act, "安装结果:" + result, Toast.LENGTH_LONG).show();
					} else {
						Log.i("helper", "正在安装->" + LoclePath1);
						//权限修改
						ShellTools ex1 = new ShellTools();
						String[] cmd2 = { "chmod", "777", LoclePath1 };
						try {
							ex1.execute(cmd2, "/");
						} catch (IOException e) {
							e.printStackTrace();
						}	
	
						Builder m = new Builder(act)
			             .setIcon(R.drawable.ic_launcher).setMessage("未检测到Helper，是否安装？")  
			             .setIcon(R.drawable.ic_launcher)  
			             .setPositiveButton("安装", new DialogInterface.OnClickListener() {  
			                 @Override  
			                 public void onClick(DialogInterface dialog, int which) {  
			                         Intent intent = new Intent(Intent.ACTION_VIEW);  
			                         intent.setDataAndType(Uri.parse("file://" + LoclePath1), "application/vnd.android.package-archive");  
			                         act.startActivity(intent);  
	
			                     }
			                 });  
						m.show();
					}
					break;	
				case INSTALL_PLAYER:
					final String LoclePath = message.getData().getString("path");
					if(MyApplication.canRunRootCommands){
						Log.i("vod", "正在安装->" + LoclePath);
						//权限修改
						ShellTools ex = new ShellTools();
						String[] cmd = { "chmod", "777", LoclePath };
						try {
							ex.execute(cmd, "/");
						} catch (IOException e) {
							e.printStackTrace();
						}	
	
						Log.i("vod", "使用命令升级apk");
						String[] cmd1 = { "pm", "install", "-r", LoclePath };
						 String result = null;
						 File dir = act.getDir("spadownload", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE
									| Context.MODE_WORLD_WRITEABLE);
						try {
							result = ex.execute(cmd1, dir.getAbsolutePath()+"/");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Log.i("vod", "安装结果:" + result);
						Toast.makeText(act, "安装结果:" + result, Toast.LENGTH_LONG).show();
					} else {
						//权限修改
						ShellTools ex = new ShellTools();
						String[] cmd = { "chmod", "777", LoclePath };
						try {
							ex.execute(cmd, "/");
						} catch (IOException e) {
							e.printStackTrace();
						}	
						Builder m1 = new Builder(act)
			             .setIcon(R.drawable.ic_launcher).setMessage("未检测到播放器，是否安装？")  
			             .setIcon(R.drawable.ic_launcher)  
			             .setPositiveButton("安装", new DialogInterface.OnClickListener() {  
			                 @Override  
			                 public void onClick(DialogInterface dialog, int which) {  
			                         Intent intent = new Intent(Intent.ACTION_VIEW);  
			                         intent.setDataAndType(Uri.parse("file://" + LoclePath), "application/vnd.android.package-archive");  
			                         act.startActivity(intent);  

			                     }
			                 });  
						m1.show();
					}
					break;		
										
				case UPDATE_SPA://升级
					// 有更新直接安装之
					if(act.app.getSoftUpdate() != null){
						boolean silentInstall = true;
						String downloadPath = MyApplication.getHostResUrl() + "/upload/"
								+ act.app.getSoftUpdate().getFilePath();
						Log.i("initData", "下载路径:" + downloadPath);
						
						if(!MyApplication.getApkVersion().startsWith("1.") && act.getMyBoard()){
							silentInstall = false;

						    ComponentName componetName = new ComponentName(  
						                    //这个是另外一个应用程序的包名  
						                    "com.ly.spahelper",
						                    //这个参数是要启动的Activity
						                    "com.ly.spahelper.UpdateActivity");  
						                try {  
						                    Intent intent1 = new Intent();  
						                    Bundle bundle = new Bundle(); 
						                    bundle.putString("downloadPath", downloadPath);
						                    intent1.putExtras(bundle);
						                    intent1.setComponent(componetName);  
						                    act.startActivity(intent1);
						                } catch (Exception e) {  
						                	Log.i("initData", "无法使用spahelper进行静默安装.");
						                	e.printStackTrace();
						                }  

						} else {
							MyApplication.localUpdatting = true;
							new WebInstaller(act, downloadPath, silentInstall).downloadAndInstall();
						}
					}
					break;
						
				}
			}
		}
	}

}
